<template>
  <a-modal
    v-model:visible="mapData.showMap"
    :closable="false"
    @before-ok="handleOk"
  >
    <div>
      <div class="address"
        ><a-typography-text>{{
          mapData.addrContent?.address
        }}</a-typography-text></div
      >
      <div id="map-container"></div>

      <div class="search-con">
        <a-select
          id="input-map"
          v-model:model-value="mapData.mapSearchData"
          v-model:input-value="mapData.address"
          placeholder="输入关键字搜索"
          allow-search
          :loading="mapData.searchLoading"
          :filter-option="false"
          @search="searchOfMap"
        >
          <a-option
            v-for="(tip, index) in mapData.tips"
            :key="index"
            :value="JSON.stringify(tip)"
          >
            <a-typography-title :heading="6">
              {{ tip.name }}
            </a-typography-title>
            <a-typography-text type="secondary">
              {{ tip.district + tip.address }}
            </a-typography-text>
          </a-option>
        </a-select>
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import AMapLoader from '@amap/amap-jsapi-loader';
  import { getRegion } from '@/api/common';
  import { reactive, watch } from 'vue';
  import config from '@/config/index';
  import { Message } from '@arco-design/web-vue';

  const mapData = reactive<any>({
    showMap: false, // 展示地图
    mapSearchData: '', // 地图搜索内容
    address: '', // 搜索的地址
    map: null, // 初始化地图
    autoComplete: null, // 初始化搜索方法
    geoCoder: null, // 初始化地理、坐标转化
    positionPicker: null, // 地图拖拽选点
    tips: [], // 搜索关键字列表
    addrContent: {}, // 回显地址信息
    searchLoading: false, // 加载状态
  });

  // 定义emit
  const emit = defineEmits(['returnAddress']);
  // 监听watch
  watch(
    () => mapData.mapSearchData,
    (newVal) => {
      if (newVal) {
        mapData.address = JSON.parse(newVal).name;
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        handleClickLocation(JSON.parse(newVal));
      }
    },
    {
      immediate: true,
    }
  );

  // 点击modal的确认会调
  // eslint-disable-next-line consistent-return
  async function handleOk(done: any) {
    const params = {
      cityCode: mapData.addrContent.regeocode.addressComponent.citycode,
      townName: mapData.addrContent.regeocode.addressComponent.township,
    };
    const res = await getRegion(params);
    if (res.data.success) {
      //  请求成功将数据整理会调给父级
      mapData.addrContent.addr = res.data.result.name.replace(/,/g, ' ');
      mapData.addrContent.addrId = res.data.result.id;
      emit('returnAddress', mapData.addrContent);
      done();
    } else {
      done(false);
    }
  }

  // 初始化init
  async function init() {
    mapData.showMap = true;
    AMapLoader.load({
      key: config.MAP_KEY, // 申请好的Web端开发者Key，首次调用 load 时必填
      version: '', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: [
        'AMap.ToolBar',
        'AMap.Autocomplete',
        'AMap.PlaceSearch',
        'AMap.Geolocation',
        'AMap.Geocoder',
      ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      AMapUI: {
        // 是否加载 AMapUI，缺省不加载
        version: '1.1', // AMapUI 缺省 1.1
        plugins: ['misc/PositionPicker'], // 需要加载的 AMapUI ui插件
      },
    }).then((AMap) => {
      /**
       * 初始化地图添加插件
       */
      mapData.map = new AMap.Map('map-container', {
        zoom: 12,
      });
      mapData.map.addControl(new AMap.ToolBar());
      mapData.map.addControl(new AMap.Autocomplete());
      mapData.map.addControl(new AMap.PlaceSearch());
      mapData.map.addControl(new AMap.Geocoder());

      // 实例化Autocomplete
      const autoOptions = {
        city: '全国',
      };
      mapData.autoComplete = new AMap.Autocomplete(autoOptions); // 搜索
      mapData.geoCoder = new AMap.Geocoder(autoOptions);

      // eslint-disable-next-line no-undef
      mapData.positionPicker = new AMapUI.PositionPicker({
        // 拖拽选点
        mode: 'dragMap',
        map: mapData.map,
      });
      mapData.positionPicker.start();
      /**
       *
       * 所有回显数据，都在positionResult里面
       * 需要字段可以查找
       *
       */
      mapData.positionPicker.on('success', (positionResult: any) => {
        mapData.addrContent = positionResult;
      });
    });
  }

  // 关闭地图
  function close() {
    mapData.showMap = false;
  }

  // 搜索地图
  function searchOfMap(val: any) {
    mapData.searchLoading = true;
    mapData.autoComplete.search(val, (status: any, result: any) => {
      // 搜索成功时，result即是对应的匹配数据
      if (status === 'complete' && result.info === 'OK') {
        mapData.tips = result.tips;
      } else {
        mapData.tips = [];
      }
      mapData.searchLoading = false;
    });
  }

  // 点击坐标
  function handleClickLocation(val: any) {
    const { location } = val;
    // 选择坐标
    if (!location) {
      Message.warning('请选择正确点位!');
      return false;
    }
    const storeCenter = [location.lng, location.lat]; // 搜索的坐标
    mapData.positionPicker.start(storeCenter);
    return true;
  }

  // 组件暴露自己的属性
  defineExpose({
    init,
    close,
  });
</script>

<style lang="less" scoped>
  #map-container {
    height: 400px;
  }

  .search-con {
    position: absolute;
    right: 20px;
    top: 64px;
    width: 260px;
  }

  .address {
    margin-bottom: 10px;
    font-weight: bold;
  }
</style>
